import os
import sys
import logging
import locale


log_level_dict = {
    'CRITICAL': logging.CRITICAL,
    'ERROR': logging.ERROR,
    'WARNING': logging.WARNING,
    'INFO': logging.INFO,
    'DEBUG': logging.DEBUG,
}

common_fmt = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
print_fmt = '%(message)s'
date_fmt = '%a, %d %b %Y %H:%M:%S'


def set_locale():
    category, locale_type = locale.getlocale()
    if category is None or locale_type is None:
        category, locale_type = locale.getdefaultlocale()
    if locale_type and 'utf' not in locale_type.lower():
        locale.setlocale(category=locale.LC_ALL, locale='.'.join([category, 'UTF-8']))
        

def main_log_init(log_dir="", log_mode='a', log_name="default_main.log", log_level='DEBUG', enable_print=False):
    set_locale()
    log_file_dir = os.getcwd()
    if os.path.exists(log_dir):
        log_file_dir = log_dir
    log_file_path = os.path.join(log_file_dir, log_name)
    set_level = log_level_dict.get(log_level, logging.DEBUG)

    logging.basicConfig(level=set_level, format=common_fmt, datefmt=date_fmt, filename=log_file_path, filemode=log_mode)

    console = logging.StreamHandler(stream=sys.stdout)
    if enable_print:
        console.setLevel(set_level)
        formatter = logging.Formatter(fmt=common_fmt)
    else:
        console.setLevel(logging.CRITICAL)
        formatter = logging.Formatter(fmt=print_fmt)
    console.setFormatter(formatter)
    logging.getLogger().addHandler(console)
    
def capture_log_init(log_dir="", log_mode='a', log_name="default_cap.log", log_level='DEBUG'):
    set_locale()
    if os.path.exists(log_dir):
        log_file_dir = log_dir
    else:
        log_file_dir = os.getcwd()
        
    log_file_path = os.path.join(log_file_dir, log_name)
    set_level = log_level_dict.get(log_level, logging.DEBUG)
    
    logging.basicConfig(level=set_level, format=common_fmt, datefmt=date_fmt, filename=log_file_path, filemode=log_mode)